package demo.Thread;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/10-08-10-15:22
 * @Description：demo.Thread     线程通信
 */
/*
wait()                       释放锁资源，让其他线程执行，自身线程进入waiting状态，等待其他线程唤醒，不然永远处于waiting状态
notify()                     唤醒其他线程（某一个），   使其他（某一个）线程从waiting  ->  runnable          hotspot 顺序唤醒线程，waiting状态的所有线程在一个队列中，每次唤醒第一个
notifyAll()                  唤醒其他所有线程
 */
public class thread_Talk {
    public static void main(String[] args) {
        myList list = new myList();
        Thread thread1 = new Thread(){
            @Override
            public void run() {
                synchronized (list){
                    for (int i = 0; i < 10; i++) {
                        if(i == 5){
                            try {
                                list.notify();
                                list.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("thread-0: " + i);
                    }
                    list.notify();
                }
            }
        };
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                synchronized (list){
                    for (int i = 10; i < 20; i++) {
                        if(i == 15){
                            try {
                                list.notify();
                                list.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("thread-1: " + i);
                    }
                    list.notify();
                }

            }
        };
        thread1.start();
        thread2.start();
    }
}
